/**
 * Java Enterprise in a Nutshell, Third Edition, 
 * by Jim Farley and William Crawford 
 * with Prakash Malani, John G. Norman, and Justin Gehtland. 
 * Copyright 2006 O'Reilly Media, Inc., 0-596-10142-2.
 *  
 * Reworked by Vladimir Tarasov, 2009-08-26.
 * Tested with JDK 1.6.
 * 
 * To run this (AccountManager) example, build the project and copy .class 
 * files in the tavl_rmi\account, tavl_rmi\accountmanager and tavl_rmi\factory
 * folders (under <project>\build\classes) together with the folder structure
 * (i.e. tavl_rmi\...) to the lab server and then enter the following command:
 * java tavl_rmi.factory.AccountManagerServer
 * 
 * If you want to run the example locally, start RMI registry first:
 * rmiregistry.exe
 * then change the port number below and press Shift+F6 to run AccountManagerServer.
 */
package tavl_rmi.factory;

import tavl_rmi.accountmanager.AccountManager;
import tavl_rmi.accountmanager.AccountManagerImpl;
import java.io.IOException;
import java.io.InputStreamReader;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

/**
 * A utility class that registers an object of the factory class 
 * AccountManagerImpl with the local RMI registry for remote access
 */
public class AccountManagerServer {

    public static void main(String argv[]) {
        // rmiregistry on the lab server listens to port 1099
        final int port = 1099;
        try {
            System.out.println("AccountManager server is started.");
            // The constructor will also create two accounts
            AccountManager mgr = new AccountManagerImpl(port);
            Registry reg = LocateRegistry.getRegistry(port);
            reg.rebind("acctManager", mgr);
            System.out.println("Registered account manager as acctManager.");

            // Keep the server process alive until Q/q is entered
            System.out.println(
                    "To end program, type Q or q, " + "then <return>.");
            char answer = '\0';
            InputStreamReader inputStreamReader =
                    new InputStreamReader(System.in);

            while (!((answer == 'q') || (answer == 'Q'))) {
                try {
                    answer = (char) inputStreamReader.read();
                } catch (IOException e) {
                    System.err.println("I/O exception: " + e.toString());
                }
            }
            System.out.println("AccountManager server is stopped.");
            System.exit(0); // necessary because remote object is created
        } catch (RemoteException re) {
            System.err.println("Remote exception while creating account manager: " + re.getMessage());
        }
    }
}